from rest_framework import serializers #导入 Django REST framework 的序列化器模块
from .models import OAUser,UserStatusChoices,OADepartment #导入定义在models中的 OAUser 模型和 UserStatusChoices 枚举

class LoginSerializer(serializers.Serializer): #自定义的序列化器
    email = serializers.EmailField(required=True,error_messages={'required':'请输入邮箱！'})   #将模型中的字段序列化，用来验证输入的邮箱密码  表示必须
    password = serializers.CharField(max_length=20,min_length=6)
    # 和数据库验证
    def validate(self, attrs):
    # attrs 是一个内部属性，它代表了序列化器中正在处理的实例的数据：
    # {
    # 'email': 'example@example.com',
    # 'password': 'mypassword'
    # }
        email = attrs.get('email')  #从序列化器的 attrs 字典中获取 email 字段的值
        password = attrs.get('password')

        if email and password:
            user = OAUser.objects.filter(email=email).first() #从数据库中查询与提供的 email 匹配的用户
            if not user :
                raise serializers.ValidationError('该邮箱不存在！')
            if not user.check_password(password): #检查密码
                raise serializers.ValidationError("密码错误！")
            #判断状态
            if user.status == UserStatusChoices.UNACTIVE:
                raise serializers.ValidationError("该用户尚未激活！")
            elif user.status == UserStatusChoices.LOCKED:
                raise serializers.ValidationError('该用户被锁定！')
            #为了减少执行SQL语句的次数，将user放到attrs中，方便在视图中使用
            attrs['user'] = user
            #在 validate 方法通过验证后，将 OAUser 模型中的用户对象添加到 attrs 字典中。这样，当序列化器执行 save 方法时，这个用户对象也会被保存
        else:
            raise serializers.ValidationError("请输入邮箱和密码！")
        return attrs

class DepartmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = OADepartment
        fields = '__all__'

class UserSerializer(serializers.ModelSerializer):
    department = DepartmentSerializer()
    class Meta:
        model = OAUser
        #fields = '__all__'
        exclude = ('password','groups','user_permissions')

from rest_framework import exceptions
class ResetPwdSerializer(serializers.Serializer):  #定义修改密码的序列化
    oldpwd = serializers.CharField(min_length=6,max_length=20)
    pwd1 = serializers.CharField(min_length=6,max_length=20)
    pwd2 = serializers.CharField(min_length=6,max_length=20)

    def validate(self,attrs): #定义验证方法 attrs表示验证的数据
        oldpwd = attrs['oldpwd']
        pwd1 = attrs['pwd1']
        pwd2 = attrs['pwd2']
        user = self.context['request'] .user
        if not user.check_password(oldpwd):
            raise exceptions.ValidationError('旧密码错误！')
        if pwd2 != pwd1:
            raise exceptions.ValidationError('两次密码不一致！')
        return attrs